from django.shortcuts import render
from django.http import JsonResponse
from django.db.models import Q

# Create your views here.
import cryptography
from rest_framework import viewsets, status
from rest_framework.decorators import api_view, action
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import (
    PostSerializer, CommentSerializer, PostListSerializer,
    LikeActionSerializer, StarActionSerializer, CommentCreateSerializer
)
from .models import Post, Comment, PostStar, PostLike
from rest_framework.permissions import IsAuthenticatedOrReadOnly, AllowAny

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from user import userser


class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = [IsAuthenticatedOrReadOnly, AllowAny]   #未认证可查看，认证后可增删改

    def list(self, request):
        """获取帖子列表"""
        posts = Post.objects.all().order_by('-created_at')
        serializer = PostListSerializer(posts, many=True)
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': serializer.data
        })


class CommentViewSet(viewsets.ModelViewSet):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    permission_classes = [IsAuthenticatedOrReadOnly, AllowAny]

    def get_queryset(self):
        post_id = self.request.query_params.get('post_id')
        if post_id:
            return Comment.objects.filter(post_id=post_id)
        return Comment.objects.all()

    def list(self, request):
        """获取帖子评论"""
        post_id = request.query_params.get('post_id')
        if not post_id:
            return Response({
                'code': 400,
                'msg': '缺少post_id参数'
            }, status=400)
        
        comments = Comment.objects.filter(post_id=post_id, parent=None).order_by('created_at')
        serializer = CommentSerializer(comments, many=True)
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': serializer.data
        })

    def create(self, request):
        """创建评论"""
        serializer = CommentCreateSerializer(data=request.data)
        if not serializer.is_valid():
            return Response({
                'code': 400,
                'msg': '参数错误',
                'errors': serializer.errors
            }, status=400)
        
        # 获取用户信息（这里需要从token中获取）
        user_id = request.data.get('user_id')
        if not user_id:
            return Response({
                'code': 400,
                'msg': '缺少user_id参数'
            }, status=400)
        
        try:
            from user.models import User
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response({
                'code': 404,
                'msg': '用户不存在'
            }, status=404)
        
        # 创建评论
        comment_data = serializer.validated_data
        comment_data['user'] = user
        comment = Comment.objects.create(**comment_data)
        
        # 更新帖子评论数
        post = comment.post
        post.comment_count = Comment.objects.filter(post=post, parent=None).count()
        post.save(update_fields=['comment_count'])
        
        # 返回创建的评论
        response_serializer = CommentSerializer(comment)
        return Response({
            'code': 200,
            'msg': '评论成功',
            'data': response_serializer.data
        })


class PostLikeAPIView(APIView):
    """点赞/取消点赞API"""
    
    def post(self, request, post_id):
        serializer = LikeActionSerializer(data=request.data)
        if not serializer.is_valid():
            return Response({
                'code': 400,
                'msg': '参数错误',
                'errors': serializer.errors
            }, status=400)
        
        action = serializer.validated_data['action']
        user_id = serializer.validated_data['user_id']
        
        try:
            post = Post.objects.get(id=post_id)
        except Post.DoesNotExist:
            return Response({
                'code': 404,
                'msg': '帖子不存在'
            }, status=404)
        
        try:
            from user.models import User
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response({
                'code': 404,
                'msg': '用户不存在'
            }, status=404)
        
        if action == 'like':
            # 点赞
            like, created = PostLike.objects.get_or_create(post=post, user=user)
            if created:
                post.like_count = PostLike.objects.filter(post=post).count()
                post.save(update_fields=['like_count'])
        else:
            # 取消点赞
            try:
                like = PostLike.objects.get(post=post, user=user)
                like.delete()
                post.like_count = PostLike.objects.filter(post=post).count()
                post.save(update_fields=['like_count'])
            except PostLike.DoesNotExist:
                pass
        
        # WebSocket广播
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            "post_sync",
            {
                "type": "post_update",
                "data": {
                    "post_id": post.id,
                    "action": action,
                    "user_id": user.id,
                    "like_count": post.like_count,
                }
            }
        )
        
        return Response({
            'code': 200,
            'msg': '操作成功',
            'data': {
                'success': True,
                'like_count': post.like_count
            }
        })


class PostStarAPIView(APIView):
    """收藏/取消收藏API"""
    
    def post(self, request, post_id):
        serializer = StarActionSerializer(data=request.data)
        if not serializer.is_valid():
            return Response({
                'code': 400,
                'msg': '参数错误',
                'errors': serializer.errors
            }, status=400)
        
        action = serializer.validated_data['action']
        user_id = serializer.validated_data['user_id']
        
        try:
            post = Post.objects.get(id=post_id)
        except Post.DoesNotExist:
            return Response({
                'code': 404,
                'msg': '帖子不存在'
            }, status=404)
        
        try:
            from user.models import User
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response({
                'code': 404,
                'msg': '用户不存在'
            }, status=404)
        
        if action == 'star':
            # 收藏
            star, created = PostStar.objects.get_or_create(post=post, user=user)
            if created:
                post.star_count = PostStar.objects.filter(post=post).count()
                post.save(update_fields=['star_count'])
        else:
            # 取消收藏
            try:
                star = PostStar.objects.get(post=post, user=user)
                star.delete()
                post.star_count = PostStar.objects.filter(post=post).count()
                post.save(update_fields=['star_count'])
            except PostStar.DoesNotExist:
                pass
        
        # WebSocket广播
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            "post_sync",
            {
                "type": "post_update",
                "data": {
                    "post_id": post.id,
                    "action": action,
                    "user_id": user.id,
                    "star_count": post.star_count,
                }
            }
        )
        
        return Response({
            'code': 200,
            'msg': '操作成功',
            'data': {
                'success': True,
                'star_count': post.star_count
            }
        })


class CommentDeleteAPIView(APIView):
    """删除评论API"""
    
    def delete(self, request, comment_id):
        try:
            comment = Comment.objects.get(id=comment_id)
        except Comment.DoesNotExist:
            return Response({
                'code': 404,
                'msg': '评论不存在'
            }, status=404)
        
        # 删除评论
        post = comment.post
        comment.delete()
        
        # 更新帖子评论数
        post.comment_count = Comment.objects.filter(post=post, parent=None).count()
        post.save(update_fields=['comment_count'])
        
        return Response({
            'code': 200,
            'msg': '删除成功',
            'data': {
                'success': True
            }
        })


def like_post(request):
    # ...数据库操作...
    # 假设 post 是当前操作的帖子对象
    # 假设 like_count 是最新点赞数
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        "post_sync",
        {
            "type": "post_update",
            "data": {
                "post_id": post.id,
                "action": "like",  # 或 "unlike"
                "user_id": request.user.id,
                "like_count": post.like_count,
            }
        }
    )
    # ...返回响应...


def star_post(request):
    if request.method == 'POST':
        post_id = request.POST.get('post_id')
        user = request.user
        try:
            post = Post.objects.get(id=post_id)
        except Post.DoesNotExist:
            return JsonResponse({'success': False, 'msg': '帖子不存在'}, status=404)
        # 判断是否已收藏
        star, created = PostStar.objects.get_or_create(post=post, user=user)
        if created:
            # 新增收藏
            post.star_count = PostStar.objects.filter(post=post).count()
            post.save(update_fields=['star_count'])
            action = 'star'
        else:
            # 已收藏则取消收藏
            star.delete()
            post.star_count = PostStar.objects.filter(post=post).count()
            post.save(update_fields=['star_count'])
            action = 'unstar'
        # WebSocket广播
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            "post_sync",
            {
                "type": "post_update",
                "data": {
                    "post_id": post.id,
                    "action": action,
                    "user_id": user.id,
                    "star_count": post.star_count,
                }
            }
        )
        return JsonResponse({"success": True, "action": action, "star_count": post.star_count})
    else:
        return JsonResponse({'success': False, 'msg': '仅支持POST请求'}, status=405)





